//
//  USUserInfoViewController.m
//  us
//
//  Created by karry on 2025/4/14.
//

#import "USUserInfoViewController.h"
#import "USUserInfoHeader.h"
#import "DTAlertTextFieldView.h"
#import "USSexChangeView.h"
#import "CharacterViewController.h"
#import "USDateAlertView.h"
@interface USUserInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) USUserInfoHeader *header;

@property (nonatomic,strong) NSArray <DTItem *>*list;

@end

@implementation USUserInfoViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"资料";
    
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadCharacter) name:USNotificationCharacter object:nil];
}

- (void)reloadCharacter {
    
    self.header.myCharacterView.character = USUser.user.character;
    self.header.relCharacterView.character = USUser.user.relCharacter;

}

- (void)setupView{
    
    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    if (self.us_tableView.tableHeaderView == nil) {
        USUserInfoHeader *header = [USUserInfoHeader jk_loadInstanceFromNib];
        self.header = header;
        [header.editBtn addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
        UIView *contentHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 200)];
        [contentHeader addSubview:header];
        [header mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        self.us_tableView.tableHeaderView = contentHeader;
 
        [self reloadCharacter];
    }


    
}

- (void)setupdata{
    
    USUser *user = [USUser user];
    

    DTItem *item0 = [DTItem itemWithTitle:@"我" image:nil tag:0 identifier:nil handle:nil];
    item0.items = @[
        [DTItem itemWithTitle:@"昵称" detailTitle:user.nickname image:nil tag:0 identifier:nil handle:nil],
        [DTItem itemWithTitle:@"性别" detailTitle:user.sexDescription image:nil tag:0 identifier:nil handle:nil],
        
        [DTItem itemWithTitle:@"生日" detailTitle:user.birthdayDescription image:nil tag:0 identifier:nil handle:nil],
        [DTItem itemWithTitle:@"ID" detailTitle:user.userId image:nil tag:0 identifier:nil handle:nil]
    ];
    
    DTItem *item1 = [DTItem itemWithTitle:@"另一半" image:nil tag:0 identifier:nil handle:nil];
    
    if (user.relStatus == 1) {
        item1.items = @[
            [DTItem itemWithTitle:@"昵称" detailTitle:user.relUser.nickname image:nil tag:0 identifier:nil handle:nil],
            [DTItem itemWithTitle:@"性别" detailTitle:user.relUser.sexDescription image:nil tag:0 identifier:nil handle:nil],
            [DTItem itemWithTitle:@"生日" detailTitle:user.relUser.birthdayDescription image:nil tag:0 identifier:nil handle:nil],
            [DTItem itemWithTitle:@"电话" detailTitle:user.relUser.mobile image:nil tag:0 identifier:nil handle:nil],
            [DTItem itemWithTitle:@"ID" detailTitle:user.relUser.userId image:nil tag:0 identifier:nil handle:nil]
        ];
        
        self.list = @[item0,item1];
    }else{
        self.list = @[item0];

    }
 
}

 
- (void)updateUserInfoWithKey:(NSString *)key
                        value:(id)value {
    [USFeedbackTool notifySuccess];

    [self startLoading];
    NSDictionary *params = @{ key : value };


    [[EMNetWork shareManager] em_post:API_EditUser
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        USUser *user = [USUser user];
        if ([user respondsToSelector:NSSelectorFromString(key)]) {
            [user setValue:value forKey:key];
        }
        [USUser saveUser:user];

        [self setupdata];

        [self loadingSuccess];
        
    } fail:^{
        
        [self loadingFailed];
        
    }];
}

- (void)editAction:(id)sender{
    [USFeedbackTool impactSoft];
    
    CharacterViewController *vc = [CharacterViewController new];
    vc.isEdit = YES;
    [self.navigationController pushViewController:vc animated:YES];

}
- (void)loadData {
    [super loadData];
    [self startLoading];

    USUser *user = [USUser user];

    RACSignal *myUserSignal = [self fetchUserWithParams:nil];

    NSMutableArray *signList = [NSMutableArray arrayWithArray:@[myUserSignal]];
    if (user.relStatus == 1) {
        RACSignal *otherUserSignal = [self fetchUserWithParams:@{@"relUserId": user.relUserId}];
        [signList addObject:otherUserSignal];
    }
    @weakify(self);
    [[RACSignal zip:signList]
     subscribeNext:^(RACTuple *tuple) {
        @strongify(self);

        USUser *myUser = tuple.first;
        
        if (user.relStatus == 1) {
            USUser *otherUser = tuple.second;
            myUser.relUser = otherUser;
            
            myUser.token = USUser.user.token;
            [USUser saveUser:myUser];
        }
        
        [self.view endEditing:YES];
        [self setupView];
        [self setupdata];
        [self loadingSuccess];
    } error:^(NSError *error) {
        @strongify(self);
        [self loadingFailed];
    }];
}

- (RACSignal *)fetchUserWithParams:(NSDictionary *)params {
 
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[EMNetWork shareManager] em_post:API_UserInfo
                                   params:params
                                      hud:nil
                               showError:YES
                                  success:^(EMApiModel *api) {
            if (!api.success || ![api.data isKindOfClass:[NSDictionary class]]) {
                [subscriber sendError:[NSError errorWithDomain:@"接口失败" code:-1 userInfo:nil]];
                return;
            }

            NSDictionary *userDict = api.data[@"user"];
            if ([userDict isKindOfClass:[NSDictionary class]]) {
                USUser *user = [USUser mj_objectWithKeyValues:userDict];
                [subscriber sendNext:user];
                [subscriber sendCompleted];
            } else {
                [subscriber sendError:[NSError errorWithDomain:@"数据格式错误" code:-1 userInfo:nil]];
            }
        } fail:^{
            [subscriber sendError:[NSError errorWithDomain:@"网络错误" code:-1 userInfo:nil]];
 
        }];
        
        return nil;
    }];
}

 

#pragma mark - <UITableViewDelegate,UITableViewDataSource>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section != 0) {
        return;
    }
    
    [USFeedbackTool impactSoft];
    
    if (indexPath.row == 0) {
        DTAlertTextFieldView *tfView = [DTAlertTextFieldView alertContentView];
        tfView.textField.placeholder = [USUser user].nickname;
        tfView.textField.jk_maxLength = 10;
        MOAlertBaseView *alertView = [[MOAlertBaseView alloc]initWithTitle:@"输入昵称" detailTitle:@"输入1-10个中文/英文数字" contentView:tfView leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:NO tapDissmiss:YES];
        @weakify(self)
        @weakify(alertView)
        alertView.didClickIndexBlock = ^(NSInteger index) {
            @strongify(self)
            @strongify(alertView)
            if (index == 1) {
                if (tfView.textField.text.length == 0) {
                    [tfView.textField jk_shake];
                    return;
                }
                NSString *nickName = tfView.textField.text;
                [self updateUserInfoWithKey:@"nickname" value:nickName];
                [alertView dismss];
            }else{
                [alertView dismss];
            }
            
        };
        
        [alertView show];
        [tfView.textField becomeFirstResponder];
    }else if (indexPath.row == 1){
        
        USSexChangeView * sexView = [USSexChangeView jk_loadInstanceFromNib];
        
        UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [MOAlertBaseView alertWidth], 80)];
        [contentView addSubview:sexView];
        
        [sexView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        sexView.sex = [USUser user].sex;
        
        MOAlertBaseView *alertView = [[MOAlertBaseView alloc]initWithTitle:@"性别" detailTitle:nil contentView:contentView leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
        
        @weakify(self)
        alertView.didClickIndexBlock = ^(NSInteger index) {
            @strongify(self)
            if (index == 1) {
                [self updateUserInfoWithKey:@"sex" value:@(sexView.sex)];
            }
        };
        
        [alertView show];
        
        
    }else if (indexPath.row == 2){
        //生日
        NSDate *date = [NSDate date];
        if ([USUser user].birthday.length > 0) {
            date = [NSDate dateWithTimeIntervalSince1970:[[USUser user].birthday integerValue]];
        }
        USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:date andSubTitle:@"设置您的生日日期" limitToNow:YES];
        [alert showInView:UIViewController.topViewController.view];
        @weakify(self)
        alert.didChooseBlock = ^(NSDate * _Nonnull date) {
            @strongify(self)

            NSTimeInterval timestamp = [date timeIntervalSince1970];
            NSInteger timestampInSeconds = (NSInteger)timestamp;
            
            [self updateUserInfoWithKey:@"birthday" value:[NSString stringWithFormat:@"%li",timestampInSeconds]];

        };
        
    }else if (indexPath.row == 3){
        //拷贝id
    
        [self.view makeToast:@"ID 已经拷贝至剪贴板"];
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.list[section].items.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    DTItem *g_item = self.list[section];
    
    if (g_item.title.length > 0) {
        UIView *view = [UIView new];
        
        UILabel *lab = [UILabel new];
        lab.font = [UIFont us_groupFont];
        lab.text = g_item.title;
        [view addSubview:lab];
        
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(16);
            make.bottom.mas_offset(-2);
        }];
        
        // 添加横线
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor blackColor];
        [view addSubview:line];
        
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(lab.mas_left);
            make.right.mas_equalTo(lab.mas_right);
            make.top.equalTo(lab.mas_bottom).offset(2);
            make.height.mas_equalTo(1);
        }];
        
        return view;
    }
    
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    DTItem *g_item = self.list[section];
    if (g_item.title.length > 0) {
        return 30;
    }
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell us_defaultCell];
    
    DTItem *item = self.list[indexPath.section].items[indexPath.row];
    
    cell.textLabel.text = item.title;
    
    cell.detailTextLabel.text = item.detailTitle;
    
    if (indexPath.section ==  0) {
        [cell us_setDefaultArrow];
    }

    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [UITableViewCell us_defaultCellRowHeight];
    
}


@end
